/**
 * Java 属性文件工具类，包括读取一个指定的文件
 */
package com.cnfangmao.util;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;


public class PropertiesUtil {
	private static Logger logger = Logger.getLogger(PropertiesUtil.class); 
	
	private static Map<String,PropertiesDelegator> mapDelegator=new HashMap<String,PropertiesDelegator>();
	
	public static class PropertiesDelegator
	{
		private Map<String,Object> mapProperties=new HashMap<String,Object>();
		
		public Object getProperty(String strKey) {
			return mapProperties.get(strKey);
		}
		
		private void setProperty(String strKey,Object objValue)
		{
			mapProperties.put(strKey, objValue);
		}
	}
	
	/****
	 * 打开一个classpath下面的properties文件
	 * @param strFile   属性文件路径
	 * @param strEncode 属性文件编码
	 * @return
	 */
	public static PropertiesDelegator readPropertiesFile4ClassPath(String packageName)
	{
		PropertiesDelegator result=null;
		Asserter.hasLength(packageName, "属性文件名不能为空！");
		
		result=mapDelegator.get(packageName);
		if(result!=null)
		{//以前载入该属性文件
			return result;
		}
		
		try 
		{
			ResourceBundle bundle=ResourceBundle.getBundle(packageName);
			
			result=generateDelegatorFromProperties(bundle);
			
			mapDelegator.put(packageName, result);
			
		} catch (Exception e) {
			logger.error(e);
		}

		return result;
	}
	
	
	/***
	 * 把Properties对象转换为PropertiesDelegator
	 * @param properties
	 * @return
	 */
	private static PropertiesDelegator generateDelegatorFromProperties(ResourceBundle bundle)
	{
		PropertiesDelegator result=null;
		Asserter.notNull(bundle, "ResourceBundle对象不能为空");
		
		result=new PropertiesDelegator();
		
		
		for(String  strKey:bundle.keySet())
		{
			result.setProperty(strKey, bundle.getString(strKey));
		}
		
		return result;
	}
}
